import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class MyServer extends JFrame {
    private ServerSocket server;
    private PrintWriter writer;
    private Socket server_socket;
    private JTextArea send_area = new JTextArea();
    private JTextArea get_area = new JTextArea();
    private JTextField text = new JTextField();
    public MyServer(){
        setTitle("向客户端发送数据");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container c = getContentPane();
        c.setLayout(new GridLayout(3,1));
        JScrollPane send_mes_scrollPane = new JScrollPane(send_area);
        c.add(send_mes_scrollPane, BorderLayout.NORTH);
        JScrollPane get_mes_scrollPane = new JScrollPane(get_area);
        c.add(get_mes_scrollPane, BorderLayout.CENTER);
        c.add(text, BorderLayout.SOUTH);
        text.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                writer.println(text.getText().trim());
                send_area.append(text.getText() + "\n");
                text.setText("");
            }
        });
    }

    public void start() {
        try {
            server = new ServerSocket(8998);
            System.out.println("服务端套接字创建好了");
            while (true) {
                System.out.println("服务端等待连接...");
                server_socket = server.accept();
                OutputStream outputStream = server_socket.getOutputStream();
                writer = new PrintWriter(outputStream, true);
                BufferedReader br = new BufferedReader(new InputStreamReader(
                        server_socket.getInputStream()));
                get_area.append("消息接收页面:\n\n");
                send_area.append("消息发送页面:\n\n");
                while (true) {
                    String s = br.readLine();
                    if ("exit".equals(s)) {
                        System.out.println("客户端退出...");
                        break;
                    }
                    get_area.append(s+"\n");
                }
                outputStream.close();
                br.close();
                server_socket.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    public static void main(String[] args) {
        MyServer server = new MyServer();
        server.setVisible(true);
        server.setSize(600, 700);
        server.start();
    }


}
